package org.qee.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 同线程加锁-解锁
 */
@Component
@Slf4j
public class ThreadLockService {

    @Autowired
    private RedisLockService redisLockService;

    private ThreadLocal<String> threadLocal = new ThreadLocal<>();

    /**
     * 加锁
     *
     * @param preKey
     * @param key
     * @param expireTime
     * @return
     */
    public boolean tryLock(String preKey, String key, Long expireTime) {
        String uniqueValue = UUID.randomUUID().toString();
        threadLocal.set(uniqueValue);
        return redisLockService.tryLock(preKey, key, uniqueValue, expireTime);
    }

    /**
     * 普通解锁
     *
     * @param preKey
     * @param key
     * @return
     */
    public boolean unLock(String preKey, String key) {
        boolean unLock = redisLockService.unLock(preKey, key, threadLocal.get());
        threadLocal.remove();
        return unLock;
    }

    // lua 解锁

    public boolean unLockInLua(String preKey, String key) {
        return redisLockService.unLockInLua(preKey, key, threadLocal.get());
    }

}
